import * as OSS from "ali-oss";
import { geApitOssStss } from "@/model/index";
function getError(action: any, option: any, xhr: any) {
  let msg;
  if (xhr.response) {
    msg = `${xhr.response.error || xhr.response}`;
  } else if (xhr.responseText) {
    msg = `${xhr.responseText}`;
  } else {
    msg = `fail to post ${action} ${xhr.status}`;
  }

  const err: any = new Error(msg);
  err.status = xhr.status;
  err.method = "post";
  err.url = action;
  return err;
}

function getBody(xhr: any) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (e) {
    return text;
  }
}

export default async function upload(option: any) {
  try {
    const credentials = await geApitOssStss();
    const client = new OSS({
      region: "oss-cn-beijing",
      accessKeyId: credentials.AccessKeyId,
      accessKeySecret: credentials.AccessKeySecret,
      stsToken: credentials.SecurityToken,
      bucket: "fe-export"
    });
    const result = await client.put(`/images-admin/${option.file.name}`, option.file);
    return result;
  } catch (err) {
    option.onError(err);
    throw err;
  }
}
